from myelin.server.nodetype.Transform import TransformMap

from MML import EventsTransform

from libmml import reset, \
    login, \
    logoff, \
    timeout, \
    permission, \
    cancel

class LoginRedirectDocument:
    
    def createDocument(self, context, source):
        path, query = context.session.getReferrer(context.request)
        if query:
            from cgi import parse_qs
            args = parse_qs(query, keep_blank_values=True)
            if args.get('action') == 'login':
                context.response_uri = '%s?no-referrer=1' % path
            else:
                context.response_uri = '%s?%s&no-referrer=1' % (path, query)
        else:
            context.response_uri = '%s?no-referrer=1' % path
        
        return '','text/plain'

class LoginEventHandler(login.EventHandler):
    
    newRedirectDocument = LoginRedirectDocument
        

class EventsTransform(EventsTransform):
    
    chain = [
        TransformMap((
            '%(xslt-base-uri)sformats/html/%(app-key)s/layout-%(method)s.xslt',
            '%(xslt-base-uri)sformats/html/%(app-key)s/domain-account/%(action)s.xslt',
            '%(xslt-base-uri)sformats/html/%(app-key)s/base.xslt',                           
            ), (
            '%(i18n-common-base-uri)sformats/html/%(app-key)s/domain-account/%(action)s.xml',
            '%(i18n-theme-base-uri)sformats/html/%(app-key)s/domain-account/%(action)s.xml',
            )
        ),
    ]
    
    events = ({
            'reset'         : (reset.EventHandler, {
                None        : chain
            }),
            'login'         : (LoginEventHandler, {
                None        : chain,
                'success'   : None,
            }),
            'cancel'        : (cancel.EventHandler, None),
            'logoff'        : (logoff.EventHandler, {
                None        : chain,
            }),
            'timeout'       : (timeout.EventHandler, {
                None        : chain,
            }),
            'permission'    : (permission.EventHandler, {
                None        : chain,
            }),
        },
    )
    
del reset, login, logoff, timeout, cancel, permission